package com.zl.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zl.common.Constant;
import com.zl.common.enumType.Category;
import com.zl.common.enumType.Column;
import com.zl.common.enumType.PublicDate;
import com.zl.common.thread.TokenThread;
import com.zl.entity.Area;
import com.zl.entity.City;
import com.zl.entity.Collect;
import com.zl.entity.Entity;
import com.zl.entity.NewsEntity;
import com.zl.entity.Province;
import com.zl.entity.QueryEntity;
import com.zl.service.CollectService;
import com.zl.service.SelectorService;
import com.zl.util.JsonMapper;
import com.zl.util.SearchUtils;
import com.zl.weixin.entity.AccessToken;
import com.zl.weixin.entity.UserClient;
import com.zl.weixin.util.WeixinUtil;

/**   
* @Title: SearchController.java 
* @Package com.zl.controller 
* @Description: 查询控制器
* @author chxl   
* @date 2015年8月10日 下午5:48:31 
* @version V1.0   
*/
@Controller
@RequestMapping("search")
@Scope("prototype")
public class SearchController {
	
	@Autowired
	private SelectorService selectorService;
	@Autowired
	private CollectService collectService;
	/**
	 * 搜索首页
	 * @return
	 */
	@RequestMapping("index")
	public String index(Model model,HttpServletRequest request){
		
		String code = request.getParameter("code");//通过微信回调得到的参数
		String appId = "wxac9a290c5dc49ed0";
    	// 第三方用户唯一凭证密钥
    	String appSecret = "24dd8e15cfeb82fc1c0ac60c8705d75c";
    	UserClient userclient = new UserClient();
    	if(StringUtils.isNotBlank(code)){
    		String openId = WeixinUtil.getOpenId(appId, appSecret, code).getOpenid();//通过code调取openid
    		AccessToken at = TokenThread.accessToken;
        	if(at!=null){
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			userclient= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", userclient); //将对象放入session中
	    		}else{
	    			userclient = (UserClient)request.getSession().getAttribute("user");
	    		}//将对象放入session中
        		
        	}else{
        		TokenThread.accessToken = WeixinUtil.getAccessToken(appId, appSecret); 
        		at = TokenThread.accessToken;
        		if(request.getSession().getAttribute("user")==null){
        			if(StringUtils.isBlank(openId)){
        				return "";
        			}
        			userclient= WeixinUtil.getUser(at.getToken(), openId);
	        		request.getSession().setAttribute("user", userclient); //将对象放入session中
	    		}else{
	    			userclient = (UserClient)request.getSession().getAttribute("user");
	    		}
        	}
    	}else{
			userclient = (UserClient)request.getSession().getAttribute("user");
    	}
    	
		List<Province> provinceList = selectorService.getAllProvince();
		model.addAttribute("provinceList", provinceList);
		
		List<Entity> categoryList  = new ArrayList<Entity>(Category.values().length);
		List<Entity> columnList = new ArrayList<Entity>(Column.values().length);
		List<Entity> publicDateList = new ArrayList<Entity>(PublicDate.values().length);
		
		for (Category t : Category.values()) {
			Entity entity = new Entity();
			entity.setId(t.getCode());
			entity.setName(t.getName());
			categoryList.add(entity);
		}
		for (Column t : Column.values()) {
			Entity entity = new Entity();
			entity.setId(t.getCode());
			entity.setName(t.getName());
			columnList.add(entity);
		}
		
		for (PublicDate t : PublicDate.values()) {
			Entity entity = new Entity();
			entity.setId(Integer.toString(t.getOrdinal()));
			entity.setName(t.getName());
			publicDateList.add(entity);
		}
		
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("columnList",columnList);
		model.addAttribute("publicDateList",publicDateList);
		return "search_zb";
	}
	
	/**
	 * 搜索转跳
	 * @return
	 */
	@RequestMapping("search")
	public String search(Model model,QueryEntity queryEntity){
		List<Province> provinceList = selectorService.getAllProvince();
		model.addAttribute("provinceList", provinceList);
		
		String modelStr = "citylist";
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		for(Province province:provinceList){
			List<Area> areaList = new ArrayList<Area>();
			Province p1 = new Province();
			p1.setId(province.getId());
			p1.setName(province.getName()+Constant.PROVINCE_APPEND);
			p1.setType(province.getType());
			p1.setCode(province.getCode());
			areaList.add(p1);
			List<City> cityList = selectorService.getCity(province.getId());
			areaList.addAll(cityList);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("city", areaList);
			mapList.add(map);
		}
		model.addAttribute(modelStr,mapList);
		
		List<Entity> columnList = new ArrayList<Entity>(Column.values().length);
		List<Entity> publicDateList = new ArrayList<Entity>(PublicDate.values().length);
		
		for (Column t : Column.values()) {
			Entity entity = new Entity();
			entity.setId(t.getCode());
			entity.setName(t.getName());
			columnList.add(entity);
		}
		
		for (PublicDate t : PublicDate.values()) {
			Entity entity = new Entity();
			entity.setId(Integer.toString(t.getOrdinal()));
			entity.setName(t.getName());
			publicDateList.add(entity);
		}
		
		model.addAttribute("columnList",columnList);
		model.addAttribute("publicDateList",publicDateList);
		model.addAttribute("queryEntity", queryEntity);
		return "search_zb_li";
	}
	
	/**
	 * ajax查询数据返回json
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public String list(QueryEntity queryEntity,HttpServletRequest request){
		//System.out.println(queryEntity.getPage());
		//queryEntity.setKeywords("多媒体");
//		UserClient user = new UserClient();
//		user.setOpenid("oFOgks6AbGnBns_u2teOtiMG711c");
		UserClient user = (UserClient)request.getSession().getAttribute("user");
		
		List<NewsEntity> list = SearchUtils.search(queryEntity);
		for(NewsEntity newsEntity:list){
			List<Collect> collectList = collectService.isExist(user.getOpenid(), newsEntity.getId());
			if(collectList!=null&&collectList.size()>0){
				newsEntity.setCollections("1");
			}else{
				newsEntity.setCollections("0");
			}
		}
		String str = JsonMapper.nonDefaultMapper().toJson(list);
		return "{\"success\":\"true\",\"msg\":"+str+"}";
	}
	
	@RequestMapping("columnSearch")
	public String columnSearch(Model model,QueryEntity queryEntity){
		model.addAttribute("queryEntity", queryEntity);
		return "list";
	}
}
